package net.wang.concurrency.test.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

@Slf4j
public class CyclicBarrierExample2 {

    public static final int threadCount = 20;

    public static CyclicBarrier barrier = new CyclicBarrier(5); //5个线程同步等待

    //用单元测试会出现问题
    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < threadCount; i++) {
            final int threadNumber = i;
            Thread.sleep(1000);
            executorService.execute(() -> {
                try {
                    out(threadNumber);
                } catch (Exception e) {
                    log.error("exception : {}", e.getMessage());
                }
            });
        }
        executorService.shutdown(); //关闭线程池
    }


    private static void out(int threadNumber) throws InterruptedException, BrokenBarrierException {
        Thread.sleep(1000);
        log.info("num = {} is ready", threadNumber);
        try {
            barrier.await(2000,TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            log.warn("exception : {}", e);
        }
        log.info("num = {} is continue", threadNumber);

    }
}
